package com.minisoft.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class BannerDownloader {

    // 城市列表接口URL
    private static final String CITY_LIST_URL = "https://zyt.cnhuafas.com/huafa/weixin/zyt/xcx/yq/public-api/api/salesCenter/getAll";
    // Banner信息接口URL模板
    private static final String BANNER_INFO_URL_TEMPLATE = "https://zyt.cnhuafas.com/huafa/weixin/zyt/xcx/yq/public-api/api/salesCenter/bannerInfo/%s/%s";
    // 图片保存目录
    private static final String SAVE_DIRECTORY = "d:/zyt-banner";
    // Banner URL保存文件
    private static final String BANNER_URL_FILE = SAVE_DIRECTORY + "/bannerUrl.txt";

    public static void main(String[] args) {
        // 创建保存目录
        FileUtil.mkdir(SAVE_DIRECTORY);

        // 获取城市列表
        String cityListJson = HttpUtil.get(CITY_LIST_URL);
        JSONObject cityListObj = JSONUtil.parseObj(cityListJson);
        JSONArray areas = cityListObj.getJSONObject("data").getJSONArray("areas");

        // 用于保存所有Banner URL
        List<String> bannerUrls = new ArrayList<>();

        // 遍历每个区域
        for (int i = 0; i < areas.size(); i++) {
            JSONObject area = areas.getJSONObject(i);
            JSONArray cityList = area.getJSONArray("list");

            // 遍历每个城市
            for (int j = 0; j < cityList.size(); j++) {
                JSONObject city = cityList.getJSONObject(j);
                String pageId = city.getStr("pageId");
                String psn = city.getStr("psn");

                // 获取Banner信息
                String bannerInfoUrl = String.format(BANNER_INFO_URL_TEMPLATE, pageId, psn);
                String bannerInfoJson = HttpUtil.get(bannerInfoUrl);
                JSONObject bannerInfoObj = JSONUtil.parseObj(bannerInfoJson);
                JSONArray banners = bannerInfoObj.getJSONArray("data");

                // 遍历每个Banner
                for (int k = 0; k < banners.size(); k++) {
                    JSONObject banner = banners.getJSONObject(k);
                    String bannerImgUrl = banner.getStr("bannerImgUrl");

                    // 下载图片
                    String fileName = bannerImgUrl.substring(bannerImgUrl.lastIndexOf("/") + 1);
                    String filePath = SAVE_DIRECTORY + "/" + fileName;
                    HttpUtil.downloadFile(bannerImgUrl, FileUtil.file(filePath));

                    // 保存Banner URL
                    bannerUrls.add(bannerImgUrl);
                }
            }
        }

        // 将所有Banner URL保存到文件
        FileUtil.writeUtf8Lines(bannerUrls, BANNER_URL_FILE);

        System.out.println("Banner图片下载完成，URL已保存到 " + BANNER_URL_FILE);
    }
}